<?php
namespace app\app\controller;

use think\Controller;

class Forgotpwd extends Controller {
    /*
     * app忘记密码
     */
    public function index() {
        if(request()->isPost()) {
            //获取相关的数据
            $data = input('post.');
            $username = $data['username'];
            $password = $data['password'];  // 已经过md5加密
            $postConfirmPwd = $data['postconfirmpwd'];
            $code = $data['code'];
            
            $ret1 = model('AppUserApply')->where('tel', '=', $username)->order('id', 'DESC')->limit(1)->select();
            $applyTime = strtotime($ret1[0]->create_time) + 6000;
            if($code != $ret1[0]->code) {
                // 验证码不正确
                return json_encode(4703);
            }
            if($applyTime < time()) {
                // 验证码过期
                return json_encode(4704);
            }
            // 验证通过
            if($code == $ret1[0]->code) {                
                $ret2 = model('AppUser')->get(['username'=>$username]);
                if($password == $postConfirmPwd) {
                    // 账户相关的信息检验
                    // 自动生成 密码的加盐字符串
                    $randCode = mt_rand(100, 10000);
                    $appUserData = [
                        'password' => md5($password . 'changyuannet'),
                        'code' => $randCode,
                    ];
                    $updateUser = model('AppUser')->updateById($appUserData, $ret2->id);
                    if(!$updateUser) {
                        // 因写入数据库，导致修改失败
                        $code = 4702;
                    } else {
                        // 密码修改成功
                        $code = 4700;
                    }
                } else {
                    // 密码与确认密码不同
                    $code = 4701;
                }                
            }
            return json_encode($code);
        }
    }
}